//------------------------------------------------------------------------------
//  <copyright file="SphereEnvironment.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//  </copyright>
//------------------------------------------------------------------------------

namespace Microsoft.Robotics.Manipulation.MotionPlanning
{
    using System;
    using Microsoft.Robotics.Geometry;
    using Microsoft.Robotics.Numerics;

    /// <summary>
    /// Environment (Obstacles) are represented as a collection of spheres. Implements a method that returns cost and gradient for a given input point. Primarily for CHOMP.
    /// </summary>
    public class SphereEnvironment : CHOMPEnvironmentRepresentation
    {
        /// <summary>
        /// Minimum allowable vector norm for computational stability (used to bound the norms as we divide by them when computing unit vectors)  
        /// </summary>
        private double minVectorNorm = 0.000001; // 1e-6 

        /// <summary>
        /// Gets or sets the list of obstacles (represented as spheres)
        /// </summary>
        public GeometryElementGroup3D Obstacles { get; set; }

        /// <summary>
        /// Computes the cost and gradient at the sphere center assuming that the environment is made up of spherical obstacles (whose centers and radii are known).
        /// Cost function restricts the robot to stay a certain threshold away from the obstacles.
        /// </summary>
        /// <param name="sphereCenter"> Center of the sphere </param>
        /// <param name="sphereRadius"> Radius of the sphere </param>
        /// <param name="epsilon"> Threshold for obstacle avoidance. We want the surface of the sphere to be at least this distance away from the nearest obstacle </param>
        /// <param name="cost"> Cost for the sphere (>= 0) </param>
        /// <param name="grad"> Gradient direction away from obstacles (at the sphere center) </param>
        /// <returns> Flag indicating if the sphere is in collision or not </returns>
        public override bool ComputeSphereCostandGradient(double[] sphereCenter, double sphereRadius, double epsilon, out double cost, out double[] grad)
        {
            // We use the CHOMP cost function (refer to CHOMP IJRR paper)
            // which penalizes a sphere based on the euclidean distance to its closest obstacle. 
            // if SDist < 0
            //    Cost = -SDist + 0.5*gradbuffer
            // else if 0 < SDist <= gradbuffer
            //    Cost = (0.5/gradbuffer) * (SDist - gradbuffer)^2
            // else
            //    Cost = 0
            // where SDist is signed distance between surface of the sphere and the nearest obstacle surface and gradbuffer is a threshold for the minimum allowable distance
            // Here, gradbuffer = 2*epsilon

            // Get the sphere position
            Vector3 vecpos = new Vector3(sphereCenter[0], sphereCenter[1], sphereCenter[2]);

            // Get a new threshold that is twice that of the input threshold (we use this for cost and gradient computation)
            double gradBuffer = 2 * epsilon;

            // Find closest obstacle to current position
            int closestId = -1;
            double closestSqrdDist = double.MaxValue;
            double sqrdDist;
            for (int i = 0; i < this.Obstacles.ElementGroup.Count; i++)
            {
                SphereElement a = ((SphereElement)this.Obstacles.ElementGroup[i]);
                sqrdDist = Vector3.Dot((vecpos - a.Location), (vecpos - a.Location));
                if (sqrdDist < closestSqrdDist)
                {
                    closestSqrdDist = sqrdDist;
                    closestId = i;
                }
            }

            // No obstacles defined
            if (closestId == -1)
            {
                cost = 0.0;
                grad = new double[3];
                return false;
            }

            // Get distance between surfaces and compute cost and gradient based on the distance
            SphereElement b = ((SphereElement)this.Obstacles.ElementGroup[closestId]);
            double dist = (vecpos - b.Location).Length(); // Length of the vector
            double surfDist = dist - sphereRadius - b.Radius;

            if (surfDist >= gradBuffer)
            {
                cost = 0.0;
                grad = new double[3];
                return false; // we are not in collision
            }
            else
            {
                grad = new double[3];
                grad[0] = vecpos.X - b.Location.X;
                grad[1] = vecpos.Y - b.Location.Y;
                grad[2] = vecpos.Z - b.Location.Z;

                // Compute the unit vector in the direction of the gradient
                dist = Math.Max(dist, this.minVectorNorm); // bound the norm so that we do not have any numerical stability issues
                MatrixExtensions.Scale(grad, 1.0 / dist);

                // We are inside obstacle
                if (surfDist <= 0.0)
                {
                    cost = -surfDist + 0.5 * gradBuffer;
                    MatrixExtensions.Scale(grad, -1.0); // unit vector pointing away from obstacle
                    return true; // we are in collision
                }
                else
                {
                    // We are within tolerance from obstacle
                    cost = (0.5 / gradBuffer) * (surfDist - gradBuffer) * (surfDist - gradBuffer);
                    double scal = ((surfDist / gradBuffer) - 1.0);
                    MatrixExtensions.Scale(grad, scal);

                    // If we are less than epsilon distance away from the obstacle, we set flag to true, else false
                    if (surfDist <= epsilon)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
        }
    }
}
